const { error } = require("console");
var express = require("express");
var router = express.Router();
const fs = require("fs");
const path = require("path");
const _ = require("lodash");

/* GET users listing. */
router.get("/", function (req, res, next) {
    const userid = req.query.userid;
    try {
        let data = fs.readFileSync(
            path.resolve(__dirname, "../data/data.json"),
            "utf8"
        );
        data = JSON.parse(data);
        const files = data.files;
        const keys = Object.keys(files);
        console.log("keys", keys);
        const response = {
            message: '',
            success: true,
            fileData: [],
        };
        // 应为对象属性是无序的，这里给给keys排序
        let array = keys.map(item => {
            const years = item.match(/\d+/g) || [];
            const stage1 = item.match(/中期/g) || [];
            const stage2 = item.match(/终期/g) || [];
            let weight = 0;
            if(years.length) {
                if(stage1.length) {
                    weight = years[0] + 1
                }
                if(stage2.length) {
                    weight = years[0] + 2
                }
            }
            const obj = {stageName: item, weight: weight, stageData: files[item]};
            return obj;
        })
        array = _.orderBy(array, ['weight'], ['desc']);
        console.log('array', array);
        response.fileData = array;
        response.message = 'Success';
        res.send(JSON.stringify(response));
    } catch (err) {
        console.error(`Got an error trying to read the file: ${err.message}`);
        res.send("error", error);
    }
});

module.exports = router;
